package com.zengdb.jdbc.handler;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;

//把结果集中唯一一条数据封成对象
public class BeanHandler<T> implements ResultSetHandler<T> {

	private Class<T> clazz;
	
	//在创建当前类的对象时，让创建者提供需要将结果集转换为具体对象的类
	public BeanHandler(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public T handler(ResultSet rs) throws Exception{
		T obj = null;
		//通过内省机制获取具体对象的类的所有属性描述对象
		PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();
		if (rs.next()) {
			obj = clazz.newInstance();
			
			for (PropertyDescriptor pd : pds) {
				String name = pd.getName();
				Object value = rs.getObject(name);
				Method method = pd.getWriteMethod();
				method.invoke(obj, new Object[]{value});
			}
		}
		return obj;
	}

}
